<?php

namespace app\admin\controller\xiservice;

use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Exception;
use fast\Tree;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Worker extends Backend
{

    /**
     * User模型对象
     * @var \app\common\model\xiservice\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\xiservice\User;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
					->where('group_id',2)
                    ->where('checkinfo',1)
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','username','avatar','mobile','service_num','idcard_front_image','idcard_back_image','can_money','freeze_money','total_money','status','createtime','pay_money','review','bond_status','credit_score','contact_name','contact_tel','service_num','idcard_front_image','idcard_back_image','extra_image','can_money','freeze_money','total_money','status','createtime','pay_money','bond_status','desc','addr','addr_detail','clothing_size','pants_size','citytxt','uptime','hat_size','waistcoat_size']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


   /**
     * 审核列表
     */
    public function audit()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where('is_sq',1)
                    ->where('checkinfo','in',[0,2])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            $adminid =$this->auth->id;
            $authgroup = Db::name('auth_group_access')->where('uid', $adminid)->field('group_id')->find();

            foreach ($list as $row) {
                $row['adminrole']=$authgroup['group_id'];
                $row->visible(['id','auth_status','adminrole','username','avatar','mobile','checkinfo','contact_name','contact_tel','service_num','idcard_front_image','idcard_back_image','extra_image','can_money','freeze_money','total_money','status','createtime','pay_money','bond_status','desc','addr','addr_detail','clothing_size','pants_size','hat_size','waistcoat_size','citytxt']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $user = $this->model->where('mobile',$params['mobile'])->find();
                if($user){
                    $this->error('用户已存在!');
                }
                $params['group_id'] = 2;
                $params['nickname'] = $params['username'];
                $params['work_start_time'] = '09:00:00';
                $params['work_end_time'] = '18:00:00';
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    //用户模块也需要新增
                    $data = $params;
                    $data['password'] =  md5(Random::alnum());
                    $data['salt'] = Random::alnum();
                    $data['status'] ='normal';
                    $usermodel = new \app\common\model\User;
                    $res = $usermodel->allowField(true)->save($data);
                    $params['user_id'] = $usermodel->id;
                    $result = $this->model->allowField(true)->save($params);


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //检测经纬度插件是否安装
        $isInstall = 0;
        $addons = get_addon_list();
        foreach ($addons as $k => &$v) {
            if($v['name']=='address'){
                 $isInstall = 1;
            }
        }      
        $this->view->assign("address", $isInstall);
        return $this->view->fetch();
    }    


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if($params['bond_status'] == '已支付'){
                $params['bond_status'] = 1;
            }else if($params['bond_status'] == '未支付'){
                $params['bond_status'] = 2; 
            }
            // echo "<pre>";
            // print_r($params);die;

            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //检测经纬度插件是否安装
        $isInstall = 0;
        $addons = get_addon_list();
        foreach ($addons as $k => &$v) {
            if($v['name']=='address'){
                 $isInstall = 1;
            }
        }    
        if($row['bond_status'] == 1){
            $row['bond_status'] = '已支付';
        }else if($row['bond_status'] == 2){
            $row['bond_status'] = '未支付';
        }
        // echo "<pre>";
        // print_r($row);die;
        
        $this->view->assign("address", $isInstall);        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

     /*
    ** 拒绝服务人员审核
     */
    public function agree($ids=null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }    
        $params['auth_status'] = 1;  
        $params['group_id'] = 2;  
        $result = $row->allowField(true)->save($params);
        if ($result !== false) {
           
            $this->success('操作成功');
        } else {
            $this->error(__('No rows were updated'));
        }
    }
    public function agree2($ids=null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }    
        $params['checkinfo'] = 1;  
        $params['auth_status'] = 3;  
        $result = $row->allowField(true)->save($params);
        if ($result !== false) {
            //推送订阅消息
            $msg = new \app\common\model\xiservice\Message();
            $msg->sendCheckUserMEssage($row->user_id, $row);
            $this->success('操作成功');
        } else {
            $this->error(__('No rows were updated'));
        }
    }
    /*
    ** 拒绝服务人员审核
     */

     public function refuse($ids=null)
     {
         $row = $this->model->get($ids);
         if (!$row) {
             $this->error(__('No Results were found'));
         }
         $adminIds = $this->getDataLimitAdminIds();
         if (is_array($adminIds)) {
             if (!in_array($row[$this->dataLimitField], $adminIds)) {
                 $this->error(__('You have no permission'));
             }
         }
         if ($this->request->isPost()) {
             $params = $this->request->post("row/a");
             if ($params) {
                 $params = $this->preExcludeFields($params);
                 $result = false;
                 $params['checkinfo'] = 2;
                 Db::startTrans();
                 try {
                     //是否采用模型验证
                     if ($this->modelValidate) {
                         $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                         $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                         $row->validateFailException(true)->validate($validate);
                     }
                     $result = $row->allowField(true)->save($params);
                     
                     Db::commit();
                 } catch (ValidateException $e) {
                     Db::rollback();
                     $this->error($e->getMessage());
                 } catch (PDOException $e) {
                     Db::rollback();
                     $this->error($e->getMessage());
                 } catch (Exception $e) {
                     Db::rollback();
                     $this->error($e->getMessage());
                 }
                 if ($result !== false) {
              
                       //推送订阅消息
                    $msg = new \app\common\model\xiservice\Message();
                    $msg->sendRefuseMEssage($row->user_id, $row);
                    $this->success();
                 } else {
                     $this->error(__('No rows were updated'));
                 }
             }
             $this->error(__('Parameter %s can not be empty', ''));
         }
         $this->view->assign("row", $row);
         return $this->view->fetch();
     } 





    public function bond($ids=null)
    {

        $row = $this->model->get($ids);
        // echo "<pre>";print_r($row);die;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $cur_money = $params['pay_money'];
                $params['pay_money'] = $row['pay_money'] - $params['pay_money']; 
                if($params['pay_money']<0){
                    $this->error('余额不足');
                }
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                      //推送订阅消息
                      $msg = new \app\common\model\xiservice\Message();
                    //   $row['cur_money']=$params['pay_money'];
                      $msg->sendMoneyMEssage($row->user_id, $row,$cur_money);
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    } 

    public function bondadd($ids=null)
    {

        $row = $this->model->get($ids);
        // echo "<pre>";print_r($row);die;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // echo "<pre>";
            // print_r($params);die;

            if ($params) {
                $params = $this->preExcludeFields($params);
                $cur_money = $params['pay_money'];
                $params['pay_money'] = $row['pay_money'] + $params['pay_money']; 
                $params['credit_score'] = 100; 
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                      //推送订阅消息
                      $msg = new \app\common\model\xiservice\Message();
                    //   $row['cur_money']=$params['pay_money'];
                      $msg->sendMoneyMEssage($row->user_id, $row,$cur_money);
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    } 

    public function reviewone($ids=null)
    {

        $row = $this->model->get($ids);
        // echo "<pre>";print_r($row);die;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['credit_score'] = $row['credit_score'] - $params['credit_score']; 
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $msg = new \app\common\model\xiservice\Message();
                    $row['cur_score']=$params['credit_score'];
                    $msg->sendScoreMEssage($row->user_id, $row, $params['credit_score']);
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    } 

         //修改师傅服务城市
         public function upsfcs($ids=null)
         {
             $row = $this->model->get($ids);
             if (!$row) {
                 $this->error(__('No Results were found'));
             }
             $adminIds = $this->getDataLimitAdminIds();
             if (is_array($adminIds)) {
                 if (!in_array($row[$this->dataLimitField], $adminIds)) {
                     $this->error(__('You have no permission'));
                 }
             }
             if ($this->request->isPost()) {
                 $params = $this->request->post("row/a");
                 $params['city_id'] = Db::name('xiservice_area')->where('id',$params['citytxt'])->find();
             
                $params['citytxt'] = $params['city_id']['name'];
                $params['city_id'] = $params['city_id']['id'];
                $currentTime = time(); // 获取当前时间戳
                $nextDay = strtotime('+365 day', $currentTime); // 将当前时间戳加一天
                $params['uptime'] = date('Y-m-d H:i:s', $nextDay);
                 if ($params) {
                     $params = $this->preExcludeFields($params);
                     $result = false;
                     Db::startTrans();
                     try {
                         //是否采用模型验证
                         if ($this->modelValidate) {
                             $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                             $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                             $row->validateFailException(true)->validate($validate);
                         }
                         $result = $row->allowField(true)->save($params);
                         
                         Db::commit();
                     } catch (ValidateException $e) {
                         Db::rollback();
                         $this->error($e->getMessage());
                     } catch (PDOException $e) {
                         Db::rollback();
                         $this->error($e->getMessage());
                     } catch (Exception $e) {
                         Db::rollback();
                         $this->error($e->getMessage());
                     }
                     if ($result !== false) {
                  
                           //推送订阅消息
                        $msg = new \app\common\model\xiservice\Message();
                        $msg->sendRefuseMEssage($row->user_id, $row);
                        $this->success();
                     } else {
                         $this->error(__('No rows were updated'));
                     }
                 }
                 $this->error(__('Parameter %s can not be empty', ''));
             }
             $this->view->assign("row", $row);
             return $this->view->fetch();
         } 
    

}
